package elitech.vietnam.myfashion.view;

import java.util.ArrayList;
import java.util.Locale;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshGridView2;
import com.huewu.pla.lib.MultiColumnListView;

import elitech.vietnam.myfashion.MainActivity;
import elitech.vietnam.myfashion.R;
import elitech.vietnam.myfashion.doinbackground.CallServiceTask;
import elitech.vietnam.myfashion.entites.Category;
import elitech.vietnam.myfashion.entites.Product;
import elitech.vietnam.myfashion.extend.AsyncTask;
import elitech.vietnam.myfashion.extend.GridViewArrayAdapter;
import elitech.vietnam.myfashion.extend.MyHorizontalScrollView;

public class ProductGridView extends LinearLayout {

	private static int mLastCategory = -1;
	private static int mLastUserId = -1;

	private MainActivity mContext;
	private MyHorizontalScrollView mScrollTab;
	private LinearLayout mLayouArrow, mLayoutCategories, mMainMenu;
	private ImageButton mFloatMenu;
	private RelativeLayout mLayoutScrollTab;
	private Category mCategory;
	private PullToRefreshGridView2 mPullRefreshGridView;
	private MultiColumnListView mGridView;
	private GridViewArrayAdapter mAdapter;
	private TextView mTxtEmpty, mTxtTitle;
	private boolean isPadding = false;
	private ArrayList<SubCategoryView> mListSub = new ArrayList<SubCategoryView>();

	public ProductGridView(MainActivity context) {
		super(context);
		this.mContext = context;
		this.mCategory = mContext.mProductCategory;
		
		LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		if (inflater != null) {
			inflater.inflate(R.layout.product_gridview, this);
		}

		mLayoutScrollTab = (RelativeLayout) this
				.findViewById(R.id.productGridView_layoutScrollTab);
		mLayoutCategories = (LinearLayout) this
				.findViewById(R.id.productGridView_layoutCategories);
		mScrollTab = (MyHorizontalScrollView) this
				.findViewById(R.id.productGridView_scrollTab);
		mLayouArrow = (LinearLayout) this
				.findViewById(R.id.productGridView_layoutArrow);
		mTxtEmpty = (TextView) this.findViewById(R.id.productGridView_txtEmpty);
		mTxtTitle = (TextView) this.findViewById(R.id.main_title);
		mMainMenu = (LinearLayout) findViewById(R.id.main_menu);
		mFloatMenu = (ImageButton) findViewById(R.id.productGridView_btnFloatMenu);
		
		mMainMenu.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mContext.callMenu();
			}
		});
		
		mFloatMenu.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mContext.callMenu();
			}
		});
		
		mScrollTab.setOnInterceptTouchEvent(new MyHorizontalScrollView.OnInterceptTouchEvent() {
			@Override
			public void onIntercept(int touchAction) {
				switch (touchAction) {
				case MotionEvent.ACTION_DOWN:
					mLayouArrow.setVisibility(View.VISIBLE);
					break;
				case MotionEvent.ACTION_UP:
					mLayouArrow.setVisibility(View.INVISIBLE);
					break;

				default:
					break;
				}
			}
		});
		
		mScrollTab.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_UP)
					mLayouArrow.setVisibility(View.INVISIBLE);
				return false;
			}
		});

		int numCol = (int) getResources().getDimension(R.dimen.grid_column);
		if (numCol == 2 || mContext.mScreenWidth > 1500) {
			numCol = 2;
			isPadding = true;
		} else
			numCol = 1;

		mPullRefreshGridView = (PullToRefreshGridView2) this
				.findViewById(R.id.productGridView_grid);
		mPullRefreshGridView.setMode(Mode.PULL_FROM_END);
		mGridView = mPullRefreshGridView.getRefreshableView();
		if (isPadding)
			mGridView.setPadding(0, 1, 1, 0);
		mGridView.setColumnCount(numCol);

		if (mContext.getLocale().equals(Locale.ENGLISH)) {
			mTxtTitle.setText(mCategory.NameEN);
		} else if (mContext.getLocale().equals(Locale.KOREA)) {
			mTxtTitle.setText(mCategory.NameKR);
		} else {
			mTxtTitle.setText(mCategory.NameVN);
		}
		if (mCategory.ProductCount > 0 && mContext.mGenderFashion == 2)
			mTxtTitle.setText(mTxtTitle.getText().toString() + " (" + mCategory.ProductCount + ")");
		else if (mCategory.MaleCount > 0 && mContext.mGenderFashion == 1)
			mTxtTitle.setText(mTxtTitle.getText().toString() + " (" + mCategory.MaleCount + ")");
		else if (mCategory.FemaleCount > 0 && mContext.mGenderFashion == 0)
			mTxtTitle.setText(mTxtTitle.getText().toString() + " (" + mCategory.FemaleCount + ")");
//		if (mCategory.Id != mLastCategory) {
//			mContext.mListProduct.clear();
//			OnResume();
//		}
		mAdapter = new GridViewArrayAdapter(mContext,
				mPullRefreshGridView.getId(), 0, mContext.mListProduct,
				isPadding);
		mPullRefreshGridView.setAdapter(mAdapter);
		LoadChildCategories();
	}

	private void ResetSubColor() {
		for (SubCategoryView sub : mListSub) {
			sub.setBackgroundResource(R.color.dark_orange);
		}
	}

	private void LoadChildCategories() {
		Category firstCategory = null;
		for (final Category category : mContext.mFullCategories) {
			if (category.ParentID == mCategory.Id &&
					((category.ProductCount > 0 && mContext.mGenderFashion == 2)
							|| (category.MaleCount > 0 && mContext.mGenderFashion == 1)
							|| (category.FemaleCount > 0 && mContext.mGenderFashion == 0))) {
				if (firstCategory == null)
					firstCategory = category;
				final SubCategoryView sub = new SubCategoryView(mContext,
						category);
				sub.setBackgroundResource(R.color.dark_orange);
				sub.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						mContext.mProductCategory = category;
						mCategory = category;

						ResetSubColor();
						sub.setBackgroundResource(R.color.light_orange);
						OnResume();
					}
				});
				sub.setLayoutParams(new LayoutParams(-2, -2, 1));
				mLayoutCategories.addView(sub);
				mListSub.add(sub);
			}
		}

		if (firstCategory != null) {
			mContext.mProductCategory = firstCategory;
			mCategory = firstCategory;

			mListSub.get(0).setBackgroundResource(R.color.light_orange);
			mLayoutScrollTab.setVisibility(View.VISIBLE);
			OnResume();
		} else {
			mLayoutScrollTab.setVisibility(View.GONE);
			OnResume();
		}
	}

	public void OnResume() {
		if (mContext.mUser == null) {
			mLastUserId = -1;
			if (mCategory.Id != mLastCategory) {
				mLastCategory = mCategory.Id;
				mContext.mListProduct.clear();
				GetProductCategory();
			}
			mAdapter = new GridViewArrayAdapter(mContext,
					mPullRefreshGridView.getId(), 0, mContext.mListProduct,
					isPadding);
			mPullRefreshGridView.setAdapter(mAdapter);
		} else {
			if (mCategory.Id != mLastCategory
					|| mContext.mUser.Id != mLastUserId) {
				mLastCategory = mCategory.Id;
				mLastUserId = mContext.mUser.Id;
				mContext.mListProduct.clear();
				GetProductCategory();
			}
			mAdapter = new GridViewArrayAdapter(mContext,
					mPullRefreshGridView.getId(), 0, mContext.mListProduct,
					isPadding);
			mPullRefreshGridView.setAdapter(mAdapter);
		}
	}

	private void GetProductCategory() {
		new CallServiceTask() {
			private ArrayList<Product> rs = new ArrayList<Product>();
			protected void onPreExecute() {
				mContext.mLoadingDialog.show();
			};
			public void work() {
				try {
					rs = service.getProductCategoryByGender(mCategory.Id, mLastUserId, mContext.mGenderFashion);
				} catch (Exception e) {
					rs = null;
				}
			};
			protected void onPostExecute(Void result) {
				if (rs == null) {
					mTxtEmpty.setVisibility(View.VISIBLE);
					mPullRefreshGridView.setVisibility(View.GONE);
					mTxtEmpty.setText(R.string.errorloadingpage);
				} else if (rs.size() != 0) {
					mTxtEmpty.setVisibility(View.GONE);
					mPullRefreshGridView.setVisibility(View.VISIBLE);
					mContext.mListProduct.clear();
					mContext.mListProduct.addAll(rs);
					mAdapter.notifyDataSetChanged();
				} else {
					mTxtEmpty.setVisibility(View.VISIBLE);
					mPullRefreshGridView.setVisibility(View.GONE);
				}
				mContext.mLoadingDialog.dismiss();
			};
		}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

}
